<?php  
class CommunicateService
{	
	public function fetchCommands()
	{
		$result = $this->_remoteCall("getCommands");
		if(!is_array($result))
		{
			return;
		}
		foreach($result as $command)
		{
			$this->executeCommand($command);
		}
		return $result;	
	}
	
	public function resetCommands()
	{
		$result = $this->_remoteCall("ResetCommands");
		return $result;	
	}
	
	public function notifyInstanceCreated($instanceConfig)
	{
		$result = $this->_remoteCall("NotifyInstanceCreated",	
									  $instanceConfig);
		return $result;
	}
	
	public function notifyInstanceStatusChanged($instanceConfig)
	{		
		$result = $this->_remoteCall("NotifyInstanceStatusChanged",	
									  $instanceConfig);
		return $result;
	}
	
	public function notifyInstanceDestroyed($instanceConfig)
	{
		$result = $this->_remoteCall("NotifyInstanceDestroyed",	
									  $instanceConfig);
		return $result;
	}
	
	public function notifyInstanceUsageUpdated($instanceConfig)
	{
		$result = $this->_remoteCall("NotifyInstanceUsageUpdated",	
									  $instanceConfig);
		return $result;
	}
	
	public function executeCommand($cmdRecord)
	{
		$cmdId 	= $cmdRecord['Id'];
		$cmd 	= $cmdRecord['command'];
		$params = $cmdRecord['parameter'];
		$cmdArr = explode("::",$cmd);
		$object = $cmdArr[0];
		$method_name = $cmdArr[1];
		
		if($params)
		{
			$params = unserialize($params);
			if(!$params)
			{
				$params = array();
			}
		}
		else
		{
			$params = array();
		}


		
		$obj = new $object;
		$obj->m_CommSvcObj = $this;
		$result = call_user_method_array($method_name, $obj, $params);
		$this->_reportResult($cmdId, $result);
		return $result;
	}
	
	protected function _remoteCall($method,$params=null)
	{		
		$uri = APPCLOUD_CONTROL_SERVER."/ws.php/appcloudcontrol/cloudService/".$method;  		   	
		$argsJson = json_encode($params);
       	$query = array(	"format=json","server_code=".SERVER_CODE,"argsJson=$argsJson" );
		$rand = rand(10000000,99999999);
       	$query[] = 'rand='.$rand;
       	$queryCheckSum = md5(SERVER_CODE.SERVER_REQUEST_KEY.$rand.$method.$argsJson);       	
		$query[] = 'checksum='.$queryCheckSum;
       	
		$httpClient = new HttpClient('POST');
		foreach ($query as $q)
			$httpClient->addQuery($q);
		$headerList = array();
		$out = $httpClient->fetchContents($uri, $headerList);	
		$cats = json_decode($out, true);

		//validate remote response
		$checksum = md5(serialize($cats['data']).SERVER_RESPONSE_KEY);
		if($cats['checksum']!=$checksum && $cats['checksum']!='')
		{
			return ; //validation failed	
		}
		else
		{
			$resultSetArray = $cats['data'];
			return $resultSetArray;
		}
	}
	
	protected function _reportResult($cmdId,$result)
	{
		$param=array('cmd_id'=>$cmdId,
					 'result'=>$result);
		$result = $this->_remoteCall("updateCommandStatus",$param);
		return $result;
	}
}
?>